<?php

namespace app\admin\logic;

use app\common\logic\Base;
use think\captcha\Captcha;
use think\facade\App;

class User extends Base {

    /**
     * @desc 登录
     * @param array $params
     * @return array|bool
     */
    public function doLogin($params) {
        $memberInfo = App::model('AuthMember')->where(['am_username' => $params['username']])->find();
        if(!$memberInfo) {
            $this->errorCode = EC_AD_AUTH_MEMBER_USERNAME_NOT_EXIST;
            return false;
        }

        $captcha = new Captcha();
        if(!$captcha->check($params['captcha'], 'login'))
        {
            App::model('common/BehaviorLog')->addLog([
                'controller' => 'User',
                'action'     => 'doLogin',
                'message'    => '输入验证码错误',
                'username'   => $memberInfo['am_username'],
                'memberId'   => $memberInfo['am_member_id'],
            ]);
           $this->errorCode = EC_AD_AUTH_MEMBER_LOGIN_CAPTCHA_ERROR;
           return false;
        }

        $md5Password = App::model('AuthMember', 'logic')->generatePassword($params['password'], $memberInfo['am_salt']);
        if(strcmp($md5Password, $memberInfo['am_password']) != 0) {
            App::model('common/BehaviorLog')->addLog([
                'controller' => 'User',
                'action'     => 'doLogin',
                'message'    => '输入不正确的密码',
                'username'   => $memberInfo['am_username'],
                'memberId'   => $memberInfo['am_member_id'],
            ]);
            $this->errorCode = EC_AD_AUTH_MEMBER_LOGIN_PASSWORD_ERROR;
            return false;
        }
        
        App::model('common/BehaviorLog')->addLog([
            'controller' => 'User',
            'action'     => 'doLogin',
            'message'    => '成功登陆管理后台',
            'username'   => $memberInfo['am_username'],
            'memberId'   => $memberInfo['am_member_id'],
        ]);
        
        session('memberId', $memberInfo['am_member_id']);
        return [
            'url' => url('index/index')
        ];
    }

}
